<?php
namespace console\controllers;

use common\service\YsUser;
use Yii;
use yii\helpers\Json;
use common\models\YwCash;
use common\models\YwUser;
use common\models\YwCashRedpack;
use common\models\YwRequest;
use common\models\MongoRequest;
use common\service\YsRedpack;
use common\models\YwCashMobile;
use common\service\YsMobile;

class CashController extends Controller {   
    
public function actionSystemcheck(){
        $this->consoleStart();
        foreach(YwCash::find()->where('money<=10 AND status=0')->each(200) as $cashInfo){
            $cashInfo->status = 1;
            $cashInfo->verify_userid = 0;
            $cashInfo->verify_at = time();
            $cashInfo->verify_remark = '系统审核通过';
            if($cashInfo->pay_way != 2 && $cashInfo->pay_way != 3){
                $cashInfo->status = 0;
                $cashInfo->verify_remark = '系统审核未通过';
                self::echoLog('非微信提现或话费提现  id:'.$cashInfo->id);
            }
            /*
            $requestSum = MongoRequest::find()->where(['user_id'=>$cashInfo->user_id])->count(1);
            $request100 = MongoRequest::find()->where(['user_id'=>$cashInfo->user_id,'status'=>100])->count(1);
            if($request100 == 0 || $request100/$requestSum > 0.35){
                $cashInfo->status = 0;
                $cashInfo->verify_remark = '系统审核未通过';
                self::echoLog('收入流水异常  id:'.$cashInfo->id);
            }
             */
            if($cashInfo->save() === false){
                self::echoLog('YwCash save false:'.print_r($cashInfo->attributes,true).' errors:'.print_r($cashInfo->errors,true));
                continue;
            }
             
            
            if($cashInfo->status != 1){
                continue;
            }
             
            /* if(empty($cashInfo) || $cashInfo->status != 1){
                self::echoLog('当前提现状态不支持发红包和话费充值 :'.print_r($cashInfo->attributes,true));
                continue;
            } */
             
//            $userWeixinInfo = \common\models\YwUserWeixin::find()->where(['user_id'=>$cashInfo->user_id])->orderBy('id ASC')->one();
            /* if ($cashInfo->pay_way == 2){
                $userWeixinInfo = YsUser::service()->canCash($cashInfo->user_id);
                if(empty($userWeixinInfo)){
                    self::echoLog('用户没有关注公众号不支持发红包 :'.print_r($cashInfo->attributes,true));
                    continue;
                }           

                $cashRedpack = \common\service\YsAccount::service()->cashRedpack($cashInfo->id,$userWeixinInfo->site_id,$userWeixinInfo->openid);
                if($cashRedpack){
                    self::echoLog('创建红包成功  id:'.$cashInfo->id);
                }else{
                    self::echoLog('创建红包失败  id:'.$cashInfo->id);
                }
            } */
            
            if ($cashInfo->pay_way == 3){
                $userInfor = YwUser::findOne($cashInfo->user_id);
                $cashMobile = \common\service\YsAccount::service()->cashMobile($cashInfo->id,$userInfor->site_id);
                if($cashMobile){
                    self::echoLog('创建话费记录成功  id:'.$cashInfo->id);
                }else{
                    self::echoLog('创建话费记录失败  id:'.$cashInfo->id);
                }
            }
        }
        $this->consoleEnd();
    }
    
    public function actionRedpack(){
        $fnLock = Yii::getAlias('@console/runtime/cash_redpack.pid');
        $fpLock = self::enterLock(array('fnLock'=>$fnLock));
        if(!$fpLock){
            self::echoLog('已经有进程运行中...');
            exit(1);
        }
        self::echoLog('脚本启动!');
        
        /*
        $sql = 'SELECT COUNT(1) AS id,site_id FROM '.YwCashRedpack::tableName().' WHERE status IN (0,1,2) GROUP BY `site_id` ORDER BY id DESC';
        $siteOrder = YwCashRedpack::findBySql($sql)->one();
         */
        
        $second = date('s');
        //$siteList = \common\classes\YcSite::classes()->siteList();
        $siteList = \common\models\YwSite::findAll(['cash_status'=>10,'blockade'=>10]);
        $siteKey = $second % count($siteList);
        $siteId = $siteList[$siteKey]->id;
        
        self::echoLog('开始处理:'.$siteList[$siteKey]->name.'提现记录');
        
        $cashRedpacks = YwCashRedpack::findAll(['status'=>[0,1,2],'site_id'=>$siteId]);
        foreach($cashRedpacks as $redpack){
            print_r($redpack->attributes);
            $cashInfo = YwCash::findOne($redpack->cash_id);
            if($cashInfo->status != 3){
                continue;
            }
            if($redpack->status == 0){
                self::echoLog('开始发送红包 cid:'.$redpack->cashInfo->id.' rid:'.$redpack->id);
                $sendCode = YsRedpack::service()->sendRedpack($redpack);
                self::echoLog('发送红包结果 cid:'.$redpack->cashInfo->id.' rid:'.$redpack->id.' '.$sendCode);
            }elseif(in_array($redpack->status,[1,2])){
                self::echoLog('开始查询红包 cid:'.$redpack->cashInfo->id.' rid:'.$redpack->id);
                $queryCode = YsRedpack::service()->queryRedpack($redpack);
                self::echoLog('查询红包结果 cid:'.$redpack->cashInfo->id.' rid:'.$redpack->id.' '.$queryCode);
            }
            sleep(3);
        }
        self::echoLog('脚本执行完成，退出!');
        self::releaseLock(array('fnLock'=>$fnLock, 'fpLock'=>$fpLock));
    }
    
    public function actionMobile(){
        $fnLock = Yii::getAlias('@console/runtime/cash_mobile.pid');
        $fpLock = self::enterLock(array('fnLock'=>$fnLock));
        if(!$fpLock){
            self::echoLog('已经有进程运行中...');
            exit(1);
        }
        self::echoLog('脚本启动!');

        $cashMobiles = YwCashMobile::findAll(['status'=>[0,1,2]]);
        foreach($cashMobiles as $mobile){
            $cashInfo = YwCash::findOne($mobile->cash_id);
            if($mobile->status == 0){
                self::echoLog('开始充值话费 cid:'.$mobile->cashInfo->id.' mid:'.$mobile->id);
                $sendCode = YsMobile::service()->sendMobile($mobile);
                self::echoLog('话费充值 cid:'.$mobile->cashInfo->id.' mid:'.$mobile->id.' '.$sendCode);
            }elseif(in_array($mobile->status,[1,2])){
                self::echoLog('开始查询话费充值 cid:'.$mobile->cashInfo->id.' mid:'.$mobile->id);
                $queryCode = YsMobile::service()->queryMobile($mobile);
                self::echoLog('查询话费充值 cid:'.$mobile->cashInfo->id.' mid:'.$mobile->id.' '.$queryCode);
            }
            sleep(3);
        }
        self::echoLog('脚本执行完成，退出!');
        self::releaseLock(array('fnLock'=>$fnLock, 'fpLock'=>$fpLock));
    }
    
    
    public function actionClear(){
    	$fnLock = Yii::getAlias('@console/runtime/cash_clear.pid');
    	$fpLock = self::enterLock(array('fnLock'=>$fnLock));
    	if(!$fpLock){
    		self::echoLog('已经有进程运行中...');
    		exit(1);
    	}
    	self::echoLog('脚本启动!');
    	$overtime = time()-7*86400;
    	$overdueCashs = YwCash::find()->where(['status'=>0])->andWhere(['<','created_at',$overtime])->all();
    	$i = 0;
    	echo count($overdueCashs)."被查询\r\n";
    	if(!empty($overdueCashs)){
    		foreach ($overdueCashs as $overdueCash){
    			$oneRecharges = \common\models\YwRecharge::find()->where(['user_id'=>$overdueCash->user_id])->andWhere(['in','type',['view']])->andWhere(['>','created_at',time()-15*86400])->orderBy('created_at DESC')->offset(0)->limit(1)->all();
    			if(empty($oneRecharges)){
    				$userCash = \common\service\YsAccount::service()->cashSuccess($overdueCash->id);
    				echo $overdueCash->user_id."半月未分享被处理\r\n";
    			}
    			$thisUser = \common\models\YwUser::findOne($overdueCash->user_id);
    			if(time() - $thisUser->updated_at> 15*86400){
    				$userCash = \common\service\YsAccount::service()->cashSuccess($overdueCash->id);
	    			echo $overdueCash->user_id.":半月未登陆被处理\r\n";
	    			$i++;
    			}
    		}
    	}
    	echo $i."被清除\r\n";
    	self::echoLog('脚本执行完成，退出!');
    	self::releaseLock(array('fnLock'=>$fnLock, 'fpLock'=>$fpLock));
    }
}
